<?php

	class Model_Category extends Zend_Db_Table_Abstract
	{
   	protected $_table;

    public function getTable()
    {
        if (null === $this->_table) {            
            require_once APPLICATION_PATH . '/models/DbTable/Category.php';
            $this->_table = new Model_DbTable_Category;
        }
        return $this->_table;
    }
   
    public function save(array $data)
    {
    		if(isset($data['id'])){
    			$id = $data['id'];
    		}else{
    			$id = 0;
    		}
    		
        $table  = $this->getTable();
        $fields = $table->info(Zend_Db_Table_Abstract::COLS);        
        foreach ($data as $field => $value) {
            if (!in_array($field, $fields)) {
                unset($data[$field]);                
            }
            
        }
        
        if($id == 0){
        	return $table->insert($data);
        }else{
        	$where = $table->getAdapter()->quoteInto('id = ?', $id);
        	return $table->update($data, $where);
        }
    }
     public function deleteCategory($id){
    	$table = $this->getTable();
    	$where = 'id = '.$id;
    	return $table->delete($where); 
    }
    public function fetchEntries()
    {       
        return $this->getTable()->fetchAll('1')->toArray();
    }
		public function fetchCategories(){	
			$table = $this->getTable();		 			
			$db = $table->getAdapter();			
			$select = $db->select()->from(array('c' => 'categories'))
									 ->join(array('a' => 'areas'), 'c.area_id = a.id',
              			array('area_en' => 'name_en', 'area_mk' => 'name_mk'));
			$stmt = $select->query();			
      return $stmt->fetchAll();
    }
    public function getCategories($sort, $dir, $start, $limit){
    	$table = $this->getTable();		 			
		$db = $table->getAdapter();			
		$select = $db->select()->from(array('c' => 'categories'))
							->join(array('a' => 'areas'), 'c.area_id = a.id',
              				array('area_id' => 'id', 'area_en' => 'name_en', 'area_mk' => 'name_mk'))
					 		->order($sort . ' ' . $dir)
              		 		->limit($limit, $start);
		$stmt = $select->query();			      
      return $stmt->fetchAll();
    }
	public function getByAreaId($area_id, $sort, $dir){
    	$table = $this->getTable();		 			
		$select = $table->select()
						->where('area_id = ?', $area_id)
						->order($sort . ' ' .$dir);    
	    return $table->fetchAll($select);
    }
    public function getTotal(){
    	$table = $this->getTable();		 			
		$db = $table->getAdapter();	
		$sql = 'SELECT COUNT(id) FROM categories';
		$res = $db->query($sql);    	
    	return $res->fetchColumn(0);
    }
    public function fetchEntry($id)
    {
        $table = $this->getTable();
        $select = $table->select()->where('id = ?', $id);    
        return $table->fetchRow($select)->toArray();
    } 	  
	}